/*
*	@file
*	@author  Thomas Kroes <t.kroes at tudelft.nl>
*	@version 1.0
*	
*	@section LICENSE
*	
*	Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*	
*	Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*	Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
*	Neither the name of the TU Delft nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
*	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*	
*	The bloom filter code is based on code snippets from chapter 8 in "iPhone 3D Programming: http://ofps.oreilly.com/titles/9780596804824/chadvanced.html"
*
*/

#pragma once

#include "vtkMotionBlurPass.h"
#include "vtkRenderPassesUtilities.h"

#include <vtkObjectFactory.h>
#include <vtkMatrix4x4.h>
#include <assert.h>
#include "vtkRenderState.h"
#include "vtkRenderer.h"
#include "vtkgl.h"
#include "vtkFrameBufferObject.h"
#include "vtkTextureObject.h"
#include "vtkShaderProgram2.h"
#include "vtkShader2.h"
#include "vtkShader2Collection.h"
#include "vtkUniformVariables.h"
#include "vtkOpenGLRenderWindow.h"
#include "vtkTextureUnitManager.h"
#include "vtkImageData.h"

#include "vtkCamera.h"
#include "vtkMath.h"
#include <vtkPixelBufferObject.h>

vtkStandardNewMacro(vtkMotionBlurPass);

// #define DEBUG_EXPORT_IMAGES

vtkMotionBlurPass::vtkMotionBlurPass()
{
	this->SceneFBO = vtkFrameBufferObject::New();		
	
	for (int i = 0; i < NO_BUFFERS; i++)
	{
		this->OffScreenFboL[i] = vtkFrameBufferObject::New();
		this->OffScreenFboR[i] = vtkFrameBufferObject::New();
	}

	this->SceneTexture = vtkTextureObject::New();

	for (int i = 0; i < NO_BUFFERS; i++)
	{
		this->OffScreenTextureL[i] = vtkTextureObject::New();
		this->OffScreenTextureR[i] = vtkTextureObject::New();
	}

	this->BloomShader		= vtkShaderProgram2::New();
	this->FilterShader		= vtkShaderProgram2::New();
	this->BlitShader		= vtkShaderProgram2::New();

	this->WindowSize[0]		= -1;
	this->WindowSize[1]		= -1;
	this->Supported			= false;
	this->SupportChecked	= false;

	printf("Loading shaders\n");
	
	this->CreateBloomShader();
	this->CreateFilterShader();
	this->CreateBlitShader();
	this->SetSensitivity(0.5f);
	this->SetIntensity(1.0f);
	this->SetFilterColor(1.0f, 1.0f, 1.0f);
}

vtkMotionBlurPass::~vtkMotionBlurPass()
{
}

void vtkMotionBlurPass::PrintSelf(ostream& os, vtkIndent indent)
{
	this->Superclass::PrintSelf(os,indent);
}

void vtkMotionBlurPass::PreRender(const vtkRenderState* RenderState)
{
	int CurrentWindowSize[2];
	RenderState->GetWindowSize(CurrentWindowSize);

	if (CurrentWindowSize[0] == this->WindowSize[0] && CurrentWindowSize[1] == this->WindowSize[1])
		return;
	
	for (int i = 0; i < 2; i++)
		this->WindowSize[i] = CurrentWindowSize[i];

	vtkOpenGLRenderWindow* RenderWindow = (vtkOpenGLRenderWindow*)RenderState->GetRenderer()->GetRenderWindow();
	
#ifdef _DEBUG
 	printf("Generating scene texture: [%d x %d]\n", this->WindowSize[0], this->WindowSize[1]);
#endif

	vtkTextureObject* SceneTexture = this->SceneTexture;

	SceneTexture->SetContext(RenderWindow);
	SceneTexture->Create2D(this->WindowSize[0], this->WindowSize[1], 4, VTK_UNSIGNED_CHAR, false);
	SceneTexture->SetMinificationFilter(vtkTextureObject::Linear);
	SceneTexture->SetLinearMagnification(true);
	SceneTexture->SetWrapS(vtkTextureObject::Clamp);
	SceneTexture->SetWrapT(vtkTextureObject::Clamp);
	
#ifdef _DEBUG
 	printf("Generating scene frame buffer object: [%d x %d]\n\n", this->WindowSize[0], this->WindowSize[1]);
#endif

	vtkFrameBufferObject* SceneFBO = this->SceneFBO;

	SceneFBO->SetContext(RenderWindow);
	SceneFBO->SetColorBuffer(0, SceneTexture);
	SceneFBO->SetActiveBuffer(0);

	const float AspectRatio = (float)this->WindowSize[0] / (float)this->WindowSize[1];
	int Sizes[4][2] = { { 64, (int)(64 / AspectRatio) }, { 32, (int)(32.0f / AspectRatio) }, { 16, (int)(16.0f / AspectRatio) }, { 8, (int)(8.0f / AspectRatio) } };

	for (int i = 0; i < NO_BUFFERS; i++)
	{
#ifdef _DEBUG
 		printf("Creating left off-screen texture %d: [%d x %d]\n", i, Sizes[i][0], Sizes[i][1]);
#endif

		vtkTextureObject* TextureL = this->OffScreenTextureL[i];

		TextureL->SetContext(RenderWindow);
		TextureL->Create2D(Sizes[i][0], Sizes[i][1], 4, VTK_UNSIGNED_CHAR, false);
		TextureL->SetMinificationFilter(vtkTextureObject::Linear);
		TextureL->SetLinearMagnification(true);
		TextureL->SetWrapS(vtkTextureObject::Clamp);
		TextureL->SetWrapT(vtkTextureObject::Clamp);

#ifdef _DEBUG
 		printf("Creating left off-screen frame buffer object %d: [%d x %d]\n\n", i, Sizes[i][0], Sizes[i][1]);
#endif

		vtkFrameBufferObject* FboL = this->OffScreenFboL[i];

		FboL->SetContext(RenderWindow);
		FboL->SetColorBuffer(0, TextureL);
		FboL->SetActiveBuffer(0);

#ifdef _DEBUG
 		printf("Creating right off-screen texture %d: [%d x %d]\n", i, Sizes[i][0], Sizes[i][1]);
#endif

		vtkTextureObject* TextureR = this->OffScreenTextureR[i];

		TextureR->SetContext(RenderWindow);
		TextureR->Create2D(Sizes[i][0], Sizes[i][1], 4, VTK_UNSIGNED_CHAR, false);
		TextureR->SetMinificationFilter(vtkTextureObject::Linear);
		TextureR->SetLinearMagnification(true);
		TextureR->SetWrapS(vtkTextureObject::Clamp);
		TextureR->SetWrapT(vtkTextureObject::Clamp);

#ifdef _DEBUG
 		printf("Creating right off-screen frame buffer object %d: [%d x %d]\n\n", i, Sizes[i][0], Sizes[i][1]);
#endif

		vtkFrameBufferObject* FboR = this->OffScreenFboR[i];

		FboR->SetContext(RenderWindow);
		FboR->SetColorBuffer(0, TextureR);
		FboR->SetActiveBuffer(0);
	}
}

void vtkMotionBlurPass::Render(const vtkRenderState* RenderState)
{
	if (!this->Enabled)
	{
		this->GetDelegatePass()->Render(RenderState);
		return;
	}

	if (this->GetDelegatePass() == NULL)
		return;

	this->PreRender(RenderState);

	if (!this->IsSupported(RenderState))
	{
		this->DelegatePass->Render(RenderState);
		this->NumberOfRenderedProps += this->DelegatePass->GetNumberOfRenderedProps();
		return;
	}
	
	vtkTextureUnitManager* TextureUnitManager = static_cast<vtkOpenGLRenderWindow *>(RenderState->GetRenderer()->GetRenderWindow())->GetTextureUnitManager();

	this->RenderDelegate(RenderState, this->WindowSize[0], this->WindowSize[1], this->WindowSize[0], this->WindowSize[1], this->SceneFBO, this->SceneTexture);
	
	this->SceneFBO->UnBind();

#ifdef DEBUG_EXPORT_IMAGES
	WriteRGBAucTextureToDisk(this->SceneTexture, "C:\\scene.png");
#endif
	
	// Fill off-screen textures with down sampled scene texture
	for (int i = 0; i < NO_BUFFERS; i++)
	{
		this->OffScreenFboL[i]->Start(this->OffScreenTextureL[i]->GetWidth(), this->OffScreenTextureL[i]->GetHeight(), false);
		{
			int SceneTextureID = TextureUnitManager->Allocate();
			vtkgl::ActiveTexture(vtkgl::TEXTURE0 + SceneTextureID);
			
			this->SceneTexture->Bind();

			this->BloomShader->GetUniformVariables()->SetUniformi("SceneTexture", 1, &SceneTextureID);
			
			this->BloomShader->Use();

			glBegin(GL_QUADS);
				glVertex2f(0.0f, 0.0f);
				glVertex2f(0.0f, 1.0f);
				glVertex2f(1.0f, 1.0f);
				glVertex2f(1.0f, 0.0f);
			glEnd();

			this->BloomShader->Restore();

			this->SceneTexture->UnBind();

			TextureUnitManager->Free(SceneTextureID);
		}

		this->OffScreenFboL[i]->UnBind();

#ifdef DEBUG_EXPORT_IMAGES
		char Name[256];
		sprintf_s(Name, 256, "C:\\Left off-screen texture (%d x %d).png", OffScreenTexture->GetWidth(), OffScreenTexture->GetHeight());
		WriteRGBAucTextureToDisk(OffScreenTexture, Name);
#endif
	}
	
	// Filter horizontally
	for (int i = 0; i < NO_BUFFERS; i++)
	{
		this->OffScreenFboR[i]->Start(this->OffScreenTextureR[i]->GetWidth(), this->OffScreenTextureR[i]->GetHeight(), false);
		{
 			int OffscreenTextureLID = TextureUnitManager->Allocate();
 			vtkgl::ActiveTexture(vtkgl::TEXTURE0 + OffscreenTextureLID);
  			this->OffScreenTextureL[i]->Bind();
			
			float Offset[2] = { 1.2f / (float)this->OffScreenTextureR[i]->GetWidth(), 0.0f };

			this->FilterShader->GetUniformVariables()->SetUniformf("OffsetX", 1, &Offset[0]);
			this->FilterShader->GetUniformVariables()->SetUniformf("OffsetY", 1, &Offset[1]);
 			this->FilterShader->GetUniformVariables()->SetUniformi("Sampler", 1, &OffscreenTextureLID);
			
			this->FilterShader->Use();

			glBegin(GL_QUADS);
				glVertex2f(0.0f, 0.0f);
				glVertex2f(1.0f, 0.0f);
				glVertex2f(1.0f, 1.0f);
				glVertex2f(0.0f, 1.0f);
			glEnd();
			
			this->FilterShader->Restore();

 			TextureUnitManager->Free(OffscreenTextureLID);
		}
	
		this->OffScreenTextureL[i]->UnBind();

		this->OffScreenFboR[i]->UnBind();

#ifdef DEBUG_EXPORT_IMAGES
		char Name[256];
		sprintf_s(Name, 256, "C:\\Right off-screen texture (%d x %d).png", this->OffScreenTextureR[i]->GetWidth(), this->OffScreenTextureR[i]->GetHeight());
		WriteRGBAucTextureToDisk(this->OffScreenTextureR[i], Name);
#endif
	}
	
	// Filter vertically
	for (int i = 0; i < NO_BUFFERS; i++)
	{
		this->OffScreenFboL[i]->Start(this->OffScreenTextureL[i]->GetWidth(), this->OffScreenTextureL[i]->GetHeight(), false);
		{
			int OffscreenTextureRID = TextureUnitManager->Allocate();
			vtkgl::ActiveTexture(vtkgl::TEXTURE0 + OffscreenTextureRID);
			this->OffScreenTextureR[i]->Bind();
			
			float Offset[2] = { 0.0f, 1.2f / (float)this->OffScreenTextureL[i]->GetHeight() };

			this->FilterShader->GetUniformVariables()->SetUniformi("Sampler", 1, &OffscreenTextureRID);
			this->FilterShader->GetUniformVariables()->SetUniformf("OffsetX", 1, &Offset[0]);
			this->FilterShader->GetUniformVariables()->SetUniformf("OffsetY", 1, &Offset[1]);
			
			this->FilterShader->Use();

			glBegin(GL_QUADS);
				glVertex2f(0.0f, 0.0f);
				glVertex2f(1.0f, 0.0f);
				glVertex2f(1.0f, 1.0f);
				glVertex2f(0.0f, 1.0f);
			glEnd();
			
			this->FilterShader->Restore();

			TextureUnitManager->Free(OffscreenTextureRID);
		}

		this->OffScreenFboL[i]->UnBind();

#ifdef DEBUG_EXPORT_IMAGES
		char Name[256];
		sprintf_s(Name, 256, "C:\\Filtered off-screen texture (%d x %d).png", this->OffScreenTextureL[i]->GetWidth(), this->OffScreenTextureL[i]->GetHeight());
		WriteRGBAucTextureToDisk(this->OffScreenTextureL[i], Name);
#endif
	}

 	glViewport(0, 0, this->WindowSize[0], this->WindowSize[1]);
	glDisable(GL_BLEND);

	// Blit the scene texture to the screen
	int SceneTextureID = TextureUnitManager->Allocate();
	vtkgl::ActiveTexture(vtkgl::TEXTURE0 + SceneTextureID);
	this->SceneTexture->Bind();
	
	this->BlitShader->GetUniformVariables()->SetUniformi("Sampler", 1, &SceneTextureID);

	this->BlitShader->Use();

	glBegin(GL_QUADS);
		glVertex2f(-1.0f, -1.0f);
		glVertex2f(1.0f, -1.0f);
		glVertex2f(1.0f, 1.0f);
		glVertex2f(-1.0f, 1.0f);
	glEnd();

	this->BlitShader->Restore();

	TextureUnitManager->Free(SceneTextureID);

	this->SceneTexture->UnBind();
	
	// Accumulate the bloom textures onto the screen
	glBlendFunc(GL_ONE, GL_ONE);
	glEnable(GL_BLEND);
	
	for (int i = 1; i < NO_BUFFERS; i++)
	{
		int BloomTextureID = TextureUnitManager->Allocate();
		vtkgl::ActiveTexture(vtkgl::TEXTURE0 + BloomTextureID);
		this->OffScreenTextureL[i]->Bind();
		
		this->BlitShader->GetUniformVariables()->SetUniformi("Sampler", 1, &BloomTextureID);

		this->BlitShader->Use();

		glBegin(GL_QUADS);
			glVertex2f(0.0f, 0.0f);
			glVertex2f(1.0f, 0.0f);
			glVertex2f(1.0f, 1.0f);
			glVertex2f(0.0f, 1.0f);
		glEnd();

		this->BlitShader->Restore();

		TextureUnitManager->Free(BloomTextureID);

		this->OffScreenTextureL[i]->UnBind();
	}
	
	glDisable(GL_BLEND);
}

void vtkMotionBlurPass::ReleaseGraphicsResources(vtkWindow* Window)
{
}

void vtkMotionBlurPass::CreateBloomShader()
{
	vtkSmartPointer<vtkShader2> BloomVS = vtkShader2::New();
	vtkSmartPointer<vtkShader2> BloomFS = vtkShader2::New();

	BloomVS->SetType(VTK_SHADER_TYPE_VERTEX);
	BloomFS->SetType(VTK_SHADER_TYPE_FRAGMENT);

	std::ifstream VS("C://Workspaces//vtkrenderpasses//source//shaders//bl_highpass.vs");
	std::string StrVS((std::istreambuf_iterator<char>(VS)), std::istreambuf_iterator<char>());
	BloomVS->SetSourceCode(StrVS.c_str());

	std::ifstream FS("C://Workspaces//vtkrenderpasses//source//shaders//bl_highpass.fs");
	std::string StrFS((std::istreambuf_iterator<char>(FS)), std::istreambuf_iterator<char>());
	BloomFS->SetSourceCode(StrFS.c_str());

	BloomVS->SetContext(this->BloomShader->GetContext());
	BloomFS->SetContext(this->BloomShader->GetContext());

	this->BloomShader->GetShaders()->AddItem(BloomVS);
	this->BloomShader->GetShaders()->AddItem(BloomFS);
}

void vtkMotionBlurPass::CreateFilterShader()
{
 	vtkSmartPointer<vtkShader2> FilterVS = vtkShader2::New();
	vtkSmartPointer<vtkShader2> FilterFS = vtkShader2::New();

 	FilterVS->SetType(VTK_SHADER_TYPE_VERTEX);
	FilterFS->SetType(VTK_SHADER_TYPE_FRAGMENT);

 	std::ifstream VS("C://Workspaces//vtkrenderpasses//source//shaders//bl_filter.vs");
 	std::string StrVS((std::istreambuf_iterator<char>(VS)), std::istreambuf_iterator<char>());
 	FilterVS->SetSourceCode(StrVS.c_str());

	std::ifstream FS("C://Workspaces//vtkrenderpasses//source//shaders//bl_filter.fs");
	std::string StrFS((std::istreambuf_iterator<char>(FS)), std::istreambuf_iterator<char>());
	FilterFS->SetSourceCode(StrFS.c_str());

 	FilterVS->SetContext(this->FilterShader->GetContext());
	FilterFS->SetContext(this->FilterShader->GetContext());

 	this->FilterShader->GetShaders()->AddItem(FilterVS);
	this->FilterShader->GetShaders()->AddItem(FilterFS);
}

void vtkMotionBlurPass::CreateBlitShader()
{
	vtkSmartPointer<vtkShader2> BlitVS = vtkShader2::New();
	vtkSmartPointer<vtkShader2> BlitFS = vtkShader2::New();

	BlitVS->SetType(VTK_SHADER_TYPE_VERTEX);
	BlitFS->SetType(VTK_SHADER_TYPE_FRAGMENT);

	std::ifstream VS("C://Workspaces//vtkrenderpasses//source//shaders//bl_blit.vs");
	std::string StrVS((std::istreambuf_iterator<char>(VS)), std::istreambuf_iterator<char>());
	BlitVS->SetSourceCode(StrVS.c_str());

	std::ifstream FS("C://Workspaces//vtkrenderpasses//source//shaders//bl_blit.fs");
	std::string StrFS((std::istreambuf_iterator<char>(FS)), std::istreambuf_iterator<char>());
	BlitFS->SetSourceCode(StrFS.c_str());

	BlitVS->SetContext(this->BlitShader->GetContext());
	BlitFS->SetContext(this->BlitShader->GetContext());

	this->BlitShader->GetShaders()->AddItem(BlitVS);
	this->BlitShader->GetShaders()->AddItem(BlitFS);
}

bool vtkMotionBlurPass::IsSupported(const vtkRenderState* RenderState)
{
	if (this->GetDelegatePass() == NULL)
		return false;

	if (!this->SupportChecked)
	{
		vtkOpenGLRenderWindow* RenderWindow = (vtkOpenGLRenderWindow*)RenderState->GetRenderer()->GetRenderWindow();

		bool LocalSupported = vtkFrameBufferObject::IsSupported(RenderWindow);

		if (!LocalSupported)
			vtkErrorMacro("FBOs are not supported by the context. Cannot blur the image.");

		if (LocalSupported)
		{
			LocalSupported = vtkTextureObject::IsSupported(RenderWindow);

			if (!LocalSupported)
				vtkErrorMacro("Texture Objects are not supported by the context. Cannot blur the image.");
		}

		if (LocalSupported)
		{
			LocalSupported = vtkShaderProgram2::IsSupported(RenderWindow);

			if (!LocalSupported)
				vtkErrorMacro("GLSL is not supported by the context. Cannot blur the image.");
		}

		if (LocalSupported)
		{
			this->BloomShader->SetContext(RenderWindow);
			this->FilterShader->SetContext(RenderWindow);
			this->BlitShader->SetContext(RenderWindow);
		}

		this->Supported			= LocalSupported;
		this->SupportChecked	= true;
	}

	return this->Supported;
}

void vtkMotionBlurPass::SetSensitivity(float Sensitivity)
{
	this->Sensitivity = max(0.0f, min(1.0f, Sensitivity));
	float Exponent = 1.0f + (10.0f - (this->Sensitivity * 10.0f));
	this->BloomShader->GetUniformVariables()->SetUniformf("Exponent", 1, &Exponent);
}

void vtkMotionBlurPass::SetIntensity(float Intensity)
{
	this->Intensity = max(0.0f, min(1.0f, Intensity));

	this->FilterShader->GetUniformVariables()->SetUniformf("Intensity", 1, &this->Intensity);
}

void vtkMotionBlurPass::SetFilterColor(float Red, float Green, float Blue)
{
	this->FilterColor[0] = max(0.0f, min(1.0f, Red));
	this->FilterColor[1] = max(0.0f, min(1.0f, Green));
	this->FilterColor[2] = max(0.0f, min(1.0f, Blue));

	this->FilterShader->GetUniformVariables()->SetUniformfv("FilterColor", 3, 1, &this->FilterColor[0]);
}